package com.block.datapush.service.apipush;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XinDaiUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaAESUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaApibUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 安易融  双授权
 */
@Service
public class XinDaiApisPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:0);
        paramMap.put("nameMd5", getMD5(memberSourceInfo.getRealname()));
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity().substring(0,memberSourceInfo.getCity().length()-1));
        paramMap.put("socialSecurity", XinDaiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());

        String iv = XinDaiUtil.getIV();
        String encrypt = XinDaiUtil.encryptCbc(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(),iv);
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("iv",iv);
        aceMap.put("data",encrypt);

        log.info("【信贷全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{} ", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷全流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        JSONObject data = resultObject.getJSONObject("data");
        Boolean check = data.getBoolean("check");
        if (code == 200 && check) {
            String productName = data.getString("productName");
            String loanName = data.getString("loanName");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("productName",productName);
            infoObject.put("companyName",loanName);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray agreementList = data.getJSONArray("agreementList");
            for (int i=0;i<agreementList.size();i++){
                JSONObject jsonObject = new JSONObject();
                String agreemenName = agreementList.getJSONObject(i).getString("name");
                String agreemenUrl = agreementList.getJSONObject(i).getString("url");
                jsonObject.put("protocalName",agreemenName);
                jsonObject.put("protocalUrl",agreemenUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("agreements",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                if (price.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price);
            }
            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);

            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    private Object getMD5(String realName) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(realName.getBytes());
            byte[] digest = md.digest();
            BigInteger no = new BigInteger(1, digest);
            String  nameMd5 = no.toString(16);
            return nameMd5;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?1:0);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity().substring(0,memberSourceInfo.getCity().length()-1));
        paramMap.put("socialSecurity", XinDaiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());


        String iv = XinDaiUtil.getIV();
        String encrypt = XinDaiUtil.decryptCbc(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey(),iv);
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("iv",iv);
        aceMap.put("data",encrypt);

        log.info("【信贷全流程】导单开始【queryUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷全流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
